package cmbc.honorcredit.entity;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CryptionData {
	private String EncryptionString;
	private final byte[] EncryptionIV = "abcdefgh".getBytes();

	public CryptionData(String EncryptionString) {
		this.EncryptionString = EncryptionString;
	}

	public byte[] EncryptionByteData(byte[] SourceData) throws Exception {
		byte[] retByte = null;

		byte[] EncryptionByte = this.EncryptionString.getBytes();
		DESKeySpec dks = new DESKeySpec(EncryptionByte);

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);

		IvParameterSpec spec = new IvParameterSpec(this.EncryptionIV);

		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

		cipher.init(1, securekey, spec);

		retByte = cipher.doFinal(SourceData);
		return retByte;
	}

	public byte[] DecryptionByteData(byte[] SourceData) throws Exception {
		byte[] retByte = null;

		byte[] EncryptionByte = this.EncryptionString.getBytes("UTF-8");
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		DESKeySpec dks = new DESKeySpec(EncryptionByte);
		SecretKey securekey = keyFactory.generateSecret(dks);

		IvParameterSpec spec = new IvParameterSpec(this.EncryptionIV);

		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

		cipher.init(2, securekey, spec);

		retByte = cipher.doFinal(SourceData);

		return retByte;
	}

	public String EncryptionStringData(String SourceData) throws Exception {
		String retStr = null;
		byte[] retByte = null;

		byte[] sorData = SourceData.getBytes();

		retByte = EncryptionByteData(sorData);

		BASE64Encoder be = new BASE64Encoder();
		retStr = be.encode(retByte);

		return retStr;
	}

	public String DecryptionStringData(String SourceData) throws Exception {
		String retStr = null;
		byte[] retByte = null;

		BASE64Decoder bd = new BASE64Decoder();
		byte[] sorData = bd.decodeBuffer(SourceData);

		retByte = DecryptionByteData(sorData);
		retStr = new String(retByte);

		return retStr;
	}

//	public static void main(String[] argv) {
//		if (argv.length != 3) {
//			System.out.println("错误的参数！CryptionData 密钥 转换方式(enc-加密 dec-解密) 数据源");
//		}
//
//		String key = "Ruimin.Ocean's Fourteen.DWMNTH21";
//		String type = "enc";
//		String src = "5t6rfe3s";
//
//		String dest = "";
//
//		CryptionData tools = new CryptionData(key);
//		try {
//			if ("enc".equals(type))
//				dest = tools.EncryptionStringData(src);
//			else if ("dec".equals(type)) {
//				dest = tools.DecryptionStringData(src);
//			}
//			System.out.println("处理结果[" + dest + "]");
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
//	}
}